Imports System.ComponentModel
Imports System.Web.UI
Imports OliverHine.Controls

Namespace OliverHine.Weather

    <DefaultProperty("Text"), ToolboxData("<{0}:Search runat=server></{0}:Search>")> Public Class Search
        Inherits System.Web.UI.WebControls.WebControl
        Implements IPostBackEventHandler : Implements INamingContainer


        Protected Overrides Sub CreateChildControls()
            Dim tSearch As New System.Web.UI.WebControls.TextBox
            With tSearch
                .ID = "tSearch"
                .Attributes.Add("onFocus", "if (this.value == '" & Helpers.Localization.GetString("Search.Text", WeatherLanguage) & "') {this.value='';}; return true;")
                .Text = Helpers.Localization.GetString("Search.Text", WeatherLanguage)
            End With
            Me.Controls.Add(tSearch)

            Dim lbLookup As New System.Web.UI.WebControls.LinkButton
            With lbLookup
                .ID = "lookup"
                .CssClass = "WeatherButton"
                .Text = Helpers.Localization.GetString("Lookup.Text", WeatherLanguage)
                AddHandler .Click, AddressOf Lookup_Click
            End With
            Me.Controls.Add(lbLookup)


            Dim dgLocations As New System.Web.UI.WebControls.DataGrid
            Dim SelectButton As New System.Web.UI.WebControls.ButtonColumn
            With SelectButton
                .ButtonType = WebControls.ButtonColumnType.LinkButton
                .Text = Helpers.Localization.GetString("Select.Text", WeatherLanguage)
                .CommandName = "select"
                .HeaderText = String.Empty
            End With

            Dim ColumnId As New System.Web.UI.WebControls.BoundColumn
            With ColumnId
                .DataField = "id"
                .HeaderText = "id"
            End With

            Dim ColumnText As New System.Web.UI.WebControls.BoundColumn
            With ColumnText
                .DataField = "loc_Text"
                .HeaderText = "Area"
            End With

            With dgLocations
                .ID = "locations"
                .Columns.Add(SelectButton)
                .Columns.Add(ColumnId)
                .Columns.Add(ColumnText)
                AddHandler .ItemCommand, AddressOf Location_ItemCommand
            End With

            Me.Controls.Add(dgLocations)
            'Me.Controls.Add(New LiteralControl(""))

            Dim lResults As New System.Web.UI.WebControls.Literal
            With lResults
                .ID = "results"
            End With

            Me.Controls.Add(lResults)
        End Sub

        Protected Sub Rendering(ByVal output As System.Web.UI.HtmlTextWriter)
            'output.Write([Text])
            output.Write(String.Format("&nbsp;<a id=""{2}"" onclick=""javascript:{0};"" href="""">{1}</a>", Page.GetPostBackEventReference(Me, "lookup"), "Lookup", "Lookup"))
        End Sub

        Public Sub RaisePostBackEvent(ByVal eventArgument As String) Implements IPostBackEventHandler.RaisePostBackEvent

            If eventArgument = "lookup" Then
                If Not MyBase.FindControl("tSearch") Is Nothing Then

                End If
            End If

        End Sub

#Region " Properties "

        Private _text As String
        <Bindable(True), Category("Appearance"), DefaultValue("")> Property [Text]() As String
            Get
                Return _text
            End Get

            Set(ByVal Value As String)
                _text = Value
            End Set
        End Property

        Private _location As String
        Public Property WeatherLocation() As String
            Get
                WeatherLocation = String.Empty
                If Not MyBase.FindControl("tSearch") Is Nothing Then
                    Dim ctl As Web.UI.WebControls.TextBox = DirectCast(MyBase.FindControl("tSearch"), Web.UI.WebControls.TextBox)
                    WeatherLocation = ctl.Text
                End If
            End Get
            Set(ByVal Value As String)
                If Not MyBase.FindControl("tSearch") Is Nothing Then
                    Dim ctl As Web.UI.WebControls.TextBox = DirectCast(MyBase.FindControl("tSearch"), Web.UI.WebControls.TextBox)
                    ctl.Text = Value
                End If
            End Set
        End Property

        Private _length As Integer
        Public Property WeatherLength() As Integer
            Get
                Return _length
            End Get
            Set(ByVal Value As Integer)
                _length = Value
            End Set
        End Property

        Private _unit As String
        Public Property WeatherUnit() As String
            Get
                Return _unit
            End Get
            Set(ByVal Value As String)
                _unit = Value
            End Set
        End Property

        Private _style As String
        Public Property WeatherStyle() As String
            Get
                Return _style
            End Get
            Set(ByVal Value As String)
                _style = Value
            End Set
        End Property

        <Bindable(True), Category("Weather Settings"), DefaultValue(5)> Public Property WeatherLanguage() As String
            Get
                Return GetViewState("lang", "en-US") '"de-AT")
            End Get
            Set(ByVal Value As String)
                SetViewState("lang", Value)
            End Set
        End Property


#End Region

        Private Sub SetViewState(ByVal Key As String, ByVal Value As String)
            Key = Me.ID & ":" & Key 'Instance-Specific StateBag Key
            If ViewState.Item(Key) Is Nothing Then
                ViewState.Add(Key, Value)
            Else
                ViewState.Item(Key) = Value
            End If
        End Sub
        Private Function GetViewState(ByVal Key As String, ByVal DefaultValue As String) As String
            Key = Me.ID & ":" & Key 'Instance-Specific StateBag Key

            If ViewState.Item(Key) Is Nothing Then
                Return DefaultValue
            Else
                Return ViewState.Item(Key).ToString()
            End If
        End Function

        Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
            MyBase.OnInit(e)
        End Sub

        Private Sub Location_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
            If e.CommandName = "select" Then
                If Not MyBase.FindControl("tSearch") Is Nothing Then
                    Dim tbx As System.Web.UI.WebControls.TextBox = CType(MyBase.FindControl("tSearch"), System.Web.UI.WebControls.TextBox)
                    tbx.Text = e.Item.Cells(1).Text

                    If Not MyBase.FindControl("locations") Is Nothing Then
                        Dim dg As System.Web.UI.WebControls.DataGrid = CType(MyBase.FindControl("locations"), System.Web.UI.WebControls.DataGrid)

                        dg.Visible = False
                    End If

                End If

                Message("<br/>" & e.Item.Cells(2).Text & Helpers.Localization.GetString("Results.Selected", WeatherLanguage), False)

                RaiseEvent FoundLocation(e.Item.Cells(1).Text)
            End If
        End Sub

        Private Sub Lookup_Click(ByVal Sender As Object, ByVal E As EventArgs)
            Dim objSearch As Object = MyBase.FindControl("tSearch")
            If Not objSearch Is Nothing Then
                Dim tbx As System.Web.UI.WebControls.TextBox = DirectCast(objSearch, System.Web.UI.WebControls.TextBox)

                Dim objLocations As Object = MyBase.FindControl("locations")
                If Not objLocations Is Nothing Then
                    Dim dg As System.Web.UI.WebControls.DataGrid = DirectCast(objLocations, System.Web.UI.WebControls.DataGrid)

                    Dim ds As DataSet = Common.Functions.SearchForLocation(tbx.Text)
                    If ds.Tables.Contains("loc") Then
                        If ds.Tables("loc").Rows.Count = 1 Then
                            '1 location found, so auto-selecting this record

                            tbx.Text = ds.Tables("loc").Rows(0)("id").ToString()
                            dg.Visible = False

                            ' display selected message
                            Message("<br/><b>" & ds.Tables("loc").Rows(0)("loc_Text").ToString() & "</b>" & Helpers.Localization.GetString("Results.Selected", WeatherLanguage), False)

                            RaiseEvent FoundLocation(tbx.Text)
                        Else
                            'multple locations were find, displaying all possible locations in a DataGrid for user selection
                            tbx.Text = ""
                            dg.AutoGenerateColumns = False
                            dg.DataSource = ds.Tables("loc")
                            dg.DataBind()
                            dg.Visible = True

                            ' display many results message
                            Message(ds.Tables("loc").Rows.Count & Helpers.Localization.GetString("Results.Many", WeatherLanguage), True)
                        End If
                    Else
                        ' display zero results message
                        Message("<br/>" & Helpers.Localization.GetString("Results.Zero", WeatherLanguage), True)
                    End If
                End If

            End If
        End Sub

        Private Sub Message(ByVal sText As String, ByVal IsError As Boolean)
            Dim objLiteral As Object = MyBase.FindControl("results")
            If Not objLiteral Is Nothing Then
                Dim lit As Web.UI.WebControls.Literal = DirectCast(objLiteral, Web.UI.WebControls.Literal)

                If IsError Then
                    lit.Text = String.Format("<font class=""NormalRed"">{0}</font>", sText)
                Else
                    lit.Text = sText
                End If
            End If
        End Sub

        Public Event FoundLocation(ByVal LocationId As String)

    End Class

End Namespace